package com.aegis.manage.service.sys.role;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.aegis.common.mybatis.base.BaseServiceImpl;
import com.aegis.common.mybatis.model.PageResult;
import com.aegis.common.utils.AssertUtil;
import com.aegis.manage.api.request.AddRoleRequest;
import com.aegis.manage.api.request.UpdateRoleRequest;
import com.aegis.manage.mapper.SysRoleMapper;
import com.aegis.manage.model.dos.SysRole;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author renogo
 * 
 * @Version 1.0
 * @Descritube
 */
@Service
public class SysRoleServiceImpl extends BaseServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {


    /**
     * @param userId
     * @return
     */
    @Override
    public List<SysRole> selectRoleByUserId(String userId) {
        return baseMapper.selectRole(userId);
    }

    @Override
    public String addRole(AddRoleRequest request) {
        validateRoleKeyUnique(request.getRoleKey());
        validateRoleNameUnique(request.getRoleName());
        SysRole sysRole = new SysRole();
        sysRole.convert(request);
        AssertUtil.operateFailed(!sysRole.insert());
        return sysRole.getId();
    }

    @Override
    public void updateRole(UpdateRoleRequest request) {
        validateRoleNameUnique(request.getRoleName());
        SysRole sysRole = new SysRole();
        sysRole.convert(request);
        AssertUtil.operateFailed(!updateById(sysRole), "更新失败");
    }


    @Override
    public PageResult<SysRole> selectRolePage(int current, int size, String keywords) {
        return selectPage(current, size, new LambdaQueryWrapper<SysRole>()
                .like(StrUtil.isNotEmpty(keywords), SysRole::getRoleName, keywords)
                .or()
                .like(StrUtil.isNotEmpty(keywords), SysRole::getRoleKey, keywords)
                .orderByAsc(SysRole::getStatus)
                .orderByAsc(SysRole::getPriority)
                .orderByAsc(SysRole::getId));
    }

    @Override
    public void delRole(String id) {
        AssertUtil.operateFailed(baseMapper.deleteById(id) <= 0, "删除失败");
    }

    protected void validateRoleNameUnique(String roleName) {
        Long l = baseMapper.selectCount(new LambdaQueryWrapper<SysRole>()
                .eq(SysRole::getRoleName, roleName));
        AssertUtil.operateFailed(l > 0, "角色名已存在");
    }


    protected void validateRoleKeyUnique(String roleKey) {
        Long l = baseMapper
                .selectCount(new LambdaQueryWrapper<SysRole>()
                        .eq(SysRole::getRoleKey, roleKey));
        AssertUtil.operateFailed(l > 0, "角色标识已存在");
    }

}
